package com.ja.openchat.ui.me;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.JsonObject;
import com.google.zxing.integration.android.IntentIntegrator;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.message.ScanActivity;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.SessionInfo;
import com.zy.openchat.core.model.user.TotalSessionsInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.ComplexSpannableStringUtils;
import com.zy.openchat.util.DensityUtil;

import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class LoginDevicesActivity extends JaBaseActivity {

    @BindView(R.id.device_name)
    TextView device_name;
    @BindView(R.id.app_name)
    TextView app_name;
    @BindView(R.id.session_info)
    TextView session_info;
    @BindView(R.id.recyclerView)
    SwipeRecyclerView recyclerView;
    @BindView(R.id.itemLayout)
    View itemLayout;
    @BindView(R.id.computer_info)
    TextView computer_info;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    @BindView(R.id.bottom_line)
    View bottom_line;

    public final SwipeMenuCreator creator = (leftMenu, rightMenu, position) -> {
        SwipeMenuItem deleteItem = new SwipeMenuItem(this)
                .setBackgroundColorResource(R.color.color_fd4e57)
                .setText(getString(R.string.logout_session))
                .setTextColor(Color.WHITE)
                .setTextSize(13)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setWidth(DensityUtil.dp2px(75));
        rightMenu.addMenuItem(deleteItem);
    };

    private LoginDeviceAdapter mAdapter;
    @Override
    public void initData() {
        setTitle(getString(R.string.device_text));
        tv_ok_right.setText(getString(R.string.edit_text));
        tv_ok_right.setTextColor(ContextCompat.getColor(this,R.color.login_btn_bg_color));
        tv_ok_right.setBackgroundColor(ContextCompat.getColor(this,R.color.transparent));
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isEditInMode = !mAdapter.isInEditMode();
                recyclerView.setSwipeItemMenuEnabled(!isEditInMode);
                mAdapter.setInEditMode(isEditInMode);
                tv_ok_right.setText(isEditInMode?getString(R.string.finish_text):getString(R.string.edit_text));
            }
        });
        bottom_line.setVisibility(View.INVISIBLE);
        computer_info.setText(ComplexSpannableStringUtils
                .getBuilder(getString(R.string.by_text))
                .append(String.format(" %s Desktop ",getString(R.string.app_name)))
                .setForegroundColor(ContextCompat.getColor(this,R.color.login_btn_bg_color))
                .append(getString(R.string.or_text))
                .append(String.format(" %s Web ",getString(R.string.app_name)))
                .setForegroundColor(ContextCompat.getColor(this,R.color.login_btn_bg_color))
                .append(String.format("%s\n%s",getString(R.string.link_text),getString(R.string.scan_qr_code)))
                .create());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new LoginDeviceAdapter();
        recyclerView.setSwipeItemMenuEnabled(true);
        recyclerView.setSwipeMenuCreator(creator);
        recyclerView.setOnItemMenuClickListener(new OnItemMenuClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge, int adapterPosition) {
                terminateSession(mAdapter.getItem(adapterPosition));
            }
        });
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if(mAdapter.isInEditMode()){
                    terminateSession(mAdapter.getItem(position));
                }
            }
        });
        mAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        load();
    }

    private void terminateSession(final SessionInfo sessionInfo){
        showProgress();
        TgResultBlock<TgResponse> resultBlock = new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if(obj!=null&&obj.ok){
                    load();
                }else{
                    ToastUtils.showShort(getString(R.string.request_error));
                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                ToastUtils.showShort(getString(R.string.request_error));
            }
        };
        if(sessionInfo==null){
            TelegramManager.getTelegramManager().terminateAllOtherSessions(this,resultBlock);
        }else{
            TelegramManager.getTelegramManager().terminateSession(this,sessionInfo.id,resultBlock);
        }
    }

    private void load(){
        TelegramManager.getTelegramManager().getActiveSessions(this, new TgResultBlock<TotalSessionsInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TotalSessionsInfo obj) {
                resetDevices(obj==null?null:obj.sessions);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void resetDevices(List<SessionInfo> obj){
        if(Common.isEmpty(obj)){
            return;
        }
        SessionInfo currentDevice = null;
        for(SessionInfo sessionInfo:obj){
            if(sessionInfo.is_current){
                currentDevice = sessionInfo;
                obj.remove(currentDevice);
                break;
            }
        }
        mAdapter.setNewInstance(obj);
        if(currentDevice!=null){
            itemLayout.setVisibility(View.VISIBLE);
            device_name.setText(currentDevice.device_model);
            app_name.setText(String.format("%s %s",getString(R.string.app_name),currentDevice.system_version));
            session_info.setText(String.format("%s · %s",currentDevice.country,getString(R.string.currently_online)));
        }else{
            itemLayout.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.logoutAllDeviceBtn,R.id.scan_qr_code_btn})
    void onClick(View view) {
        switch (view.getId()){
            case R.id.logoutAllDeviceBtn:
                terminateSession(null);
                break;
            case R.id.scan_qr_code_btn:
                IntentIntegrator integrator = new IntentIntegrator(this);
                integrator.setPrompt("");
                integrator.setBeepEnabled(false);
                integrator.setBarcodeImageEnabled(false);
                integrator.setOrientationLocked(false);
                integrator.setCaptureActivity(ScanActivity.class);
                integrator.initiateScan();
                break;
        }
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_login_devices;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainActivity.onScanResult(this, requestCode, resultCode, data);
    }
    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }
}
